import { StorageUtil } from '@/utils/storage';
import { getInfo } from '@/api/user';
import { login, logout } from '@/api/login';
import type { Commit } from 'vuex';
import type { UserState, UserMutations, UserActions, UserGetters } from './user.type';

const loginSuccess = (commit: Commit, { token }: { token: string }) => {
  const expiryTime = 30 * 86400;
  StorageUtil.setLocalStorage('ACCESS_TOKEN', token, expiryTime);
  commit('SET_TOKEN', token);
};

const state: UserState = {
  token: '',
  userInfo: null,
};

const mutations: UserMutations = {
  SET_TOKEN: (state: UserState, value: string) => {
    state.token = value;
  },
  SET_USER: (state: UserState, value: any) => {
    state.userInfo = value;
  },
};

const actions: UserActions = {
  Login({ commit }: { commit: Commit }, data: any) {
    return new Promise((resolve, reject) => {
      login(data).then((response: any) => {
        const result = response;
        loginSuccess(commit, result);
        resolve(response);
      }).catch(reject);
    });
  },

  Info({ commit, state }: { commit: Commit; state: UserState }) {
    // if (state.userInfo) {
    //   return new Promise((resolve) => {
    //     resolve(state.userInfo);
    //   });
    // }
    return new Promise((resolve, reject) => {
      getInfo().then((response: any) => {
        const result = response;
        commit('SET_USER', result.user);
        resolve(response.user);
      }).catch(reject);
    });
  },

  Logout({ commit }: { commit: Commit }, data: any) {
    return new Promise((resolve, reject) => {
      logout().then((response: any) => {
        StorageUtil.removeLocalStorage('ACCESS_TOKEN');
        commit('SET_TOKEN', '');
        resolve(response);
      }).catch(reject);
    });
  },
};

const getters: UserGetters = {
  getToken: (state: UserState) => state.token,
  getUserInfo: (state: UserState) => state.userInfo,
};

export default {
  state,
  mutations,
  actions,
  getters
};